package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.ResponseProcessorImp;

import java.util.Date;
import java.util.concurrent.BlockingQueue;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressValue;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.WriteSingleRegisterRequest;
import net.wimpi.modbus.msg.WriteSingleRegisterResponse;
import net.wimpi.modbus.procimg.SimpleRegister;

public class WriteSingleRegisterResponseProcessor extends
		AbstractResponseProcessor {

	@Override
	public void processResponse(ModbusRequest req, ModbusResponse res, BlockingQueue<AddressValue> queue) {
		// TODO WriteSingleRegisterResponseProcessor error IllegalAddressException
		if(res instanceof WriteSingleRegisterResponse && req instanceof WriteSingleRegisterRequest){
			
			int regValue = ((WriteSingleRegisterResponse) res).getRegisterValue();
			int ref = ((WriteSingleRegisterResponse) res).getReference();
			Date date = new Date();


			AddressValue newValue = new AddressValue();
			newValue.setAddress(ref);
			newValue.setAddressType(AddressType.HOLDING_REGISTER);
			newValue.setDate(date);
			newValue.setValue(regValue);
			
			queue.add(newValue);
			
			getImage().setRegister(ref,new SimpleRegister(regValue),date);
			
			/*
			if( getDeciveDAO() != null )
					getDeciveDAO().saveValue( getDevice(), ref , regValue , AddressType.HOLDING_REGISTER );
					*/
					
		}	
	}

}
